#!/usr/local/bin/python3
# coding=utf-8


import click
import os
from pathlib import Path
from click.types import File
from click.utils import open_file
import subprocess


def selecte_crash_str(text: str = ""):
    return text.startswith("0x")


class CrashModel:
    def __init__(self,first_key, second_key):
        self.first_key = first_key
        self.second_key = second_key

def split_carsh_log(text: str = "") -> CrashModel:
    some_arr = text.split(" ")
    result_arr = list(filter(selecte_crash_str,some_arr))
    if len(result_arr) == 2: 
        model = CrashModel(result_arr[0], result_arr[1])
        return model
    else:
        print("crash数据不合法")


@click.command()
@click.option("--file", "-f", help="请输入要解析的文件")
@click.option("--dysm", "-d", default = "DUApp.app.dSYM",help="请输入dysm文件名")
@click.option("--binary", "-b",default = "DUApp", help="二进制文件名")

def enjoy_crash(file, dysm,binary):
    pwd = os.getcwd()
    full_path = pwd + "/" + file

    full_dysm_path = pwd + "/" + dysm + "/Contents/Resources/DWARF/" + binary

    result_path = pwd + "/enjoy_crash_log.txt"
    if os.path.exists(result_path):
        os.remove(result_path)

    im_file = Path(full_path)
    crash_log_arr = ""
    if im_file.is_file():
        with open(file, "r") as f:
            crash_log_arr = f.readlines()

    clear_arr = []
    clear_arr = list(filter(selecte_crash_str,crash_log_arr))

    total_res = ""
    for item in clear_arr: 
            model = split_carsh_log(item)
            cmd_str = "atos -arch arm64 -o {0} -l {1} {2}".format(full_dysm_path,model.second_key,model.first_key)
            output = subprocess.getoutput(cmd_str)
            total_res = total_res + output  + "\n"
            print(output)

    with open(result_path,"w") as f:
        f.write(total_res)
    
    print("******enjoy carsh log create success******")

    

if __name__ == "__main__":
    enjoy_crash()